package com.lizonghui.googleplay.control;

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.lizonghui.googleplay.R;
import com.lizonghui.googleplay.base.BaseHolder;
import com.lizonghui.googleplay.config.Constants;
import com.lizonghui.googleplay.utils.UIUtils;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by Administrator on 2016/6/22.
 * 得到轮播图的holder
 */
public class HomePictureHolder extends BaseHolder<List<String>> implements ViewPager.OnPageChangeListener {


    @Bind(R.id.item_home_picture_pager)
    ViewPager mItemHomePicturePager;
    @Bind(R.id.item_home_picture_container_indicator)
    LinearLayout mItemHomePictureContainerIndicator;
    private List<String> mPictures;
    private ImageView mIvIndicator;

    /**
     * @return
     * @des 告知你所能提供的视图/持有视图是啥
     */
    @Override
    public View initHolderView() {
        View rootView = View.inflate(UIUtils.getContext(), R.layout.item_home_picture, null);
        //找孩子
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    /**
     * @param pictures
     * @des 进行数据绑定
     */
    @Override
    public void refreshHolderView(List<String> pictures) {
        mPictures = pictures;
        //data-->局部变量提供进来
        //view-->成员变量（找孩子）
        mItemHomePicturePager.setAdapter(new HomePictureAdapter());

        //处理indicator的内容
        for (int i = 0; i < mPictures.size(); i++) {
            mIvIndicator = new ImageView(UIUtils.getContext());
            mIvIndicator.setImageResource(R.drawable.indicator_normal);
            if (i == 0) {//初始化刚开始第一个视图的点点为选中状态
                mIvIndicator.setImageResource(R.drawable.indicator_selected);
            }
            int width = UIUtils.dip2px(5);//dip转px
            int heigtht = UIUtils.dip2px(5);
            //设置点点的布局视图参数
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, heigtht);
            params.leftMargin = UIUtils.dip2px(5);
            params.bottomMargin = UIUtils.dip2px(5);
            mItemHomePictureContainerIndicator.addView(mIvIndicator, params);

        }

        //滑动的时候切换indicator。  类实现接口，并实现3个方法
        mItemHomePicturePager.setOnPageChangeListener(this);

        //实现无限轮播 1 修改getCount为最大值Integer.MAX_VALUE 2有position处 position = position % mPictures.size();
        int diff = Integer.MAX_VALUE / 2 % mPictures.size();//看给的位置和0位置偏差了多少
        int index = Integer.MAX_VALUE / 2 - diff;//因为给的值可能出现偏差，所以修改偏差(或者+)，使得第一个图为0
        mItemHomePicturePager.setCurrentItem(index);//解决开始第一个轮播无法向左滑,给一个中间值。

        //自动轮播 2中方式（智慧北京）
        final AutoScrollTask autoScrollTask = new AutoScrollTask();
        autoScrollTask.start();


        //按下去时候停止轮播
        mItemHomePicturePager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        autoScrollTask.stop();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        autoScrollTask.start();
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }

    class AutoScrollTask implements Runnable{
        public void start(){
            UIUtils.getHandler().postDelayed(this,3000);
        }
        public void stop(){
            UIUtils.getHandler().removeCallbacks(this);
        }
        @Override
        public void run() {
            int currentItem = mItemHomePicturePager.getCurrentItem();
            currentItem++;
            mItemHomePicturePager.setCurrentItem(currentItem);//产生轮播动画
            start();
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        position = position % mPictures.size();
        //1还原所有的
        //2选中特定的
        for (int j = 0; j < mPictures.size(); j++) {
            ImageView indicator = (ImageView) mItemHomePictureContainerIndicator.getChildAt(j);
            indicator.setImageResource(R.drawable.indicator_normal);
            if (position == j) {
                indicator.setImageResource(R.drawable.indicator_selected);
            }

        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    class HomePictureAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            if (mPictures != null) {
//                return mPictures.size();
                return Integer.MAX_VALUE;
            }
            return 0;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        //初始化轮播图的Item
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            position = position % mPictures.size();//取得当前轮播的position

            ImageView iv = new ImageView(UIUtils.getContext());
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            //data
            String url = mPictures.get(position);
            //加载图片
            Picasso.with(UIUtils.getContext()).load(Constants.URLS.IMABASEURL + url).into(iv);
            container.addView(iv);
            return iv;
        }

        //移除孩子，优化效率
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }


}
